package cn.iocoder.yudao.module.member.service.student;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.EmailInfo;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.encryption.EncryptionUtil;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.common.util.mail.MailUtils;
import cn.iocoder.yudao.framework.common.util.string.StrUtils;
import cn.iocoder.yudao.framework.common.validation.Mobile;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.member.controller.admin.student.vo.*;
import cn.iocoder.yudao.module.member.controller.admin.studentEducationalExperience.vo.StudentEducationalExperienceRespVO;
import cn.iocoder.yudao.module.member.controller.app.user.vo.AppUserUpdateMobileReqVO;
import cn.iocoder.yudao.module.member.convert.student.StudentConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.curriculumVitaeSendRecord.CurriculumVitaeSendRecordDO;
import cn.iocoder.yudao.module.member.dal.dataobject.interviewInvite.InterviewInviteDO;
import cn.iocoder.yudao.module.member.dal.dataobject.student.StudentDO;
import cn.iocoder.yudao.module.member.dal.dataobject.studentCurriculumVitae.StudentCurriculumVitaeDO;
import cn.iocoder.yudao.module.member.dal.dataobject.studentEducationalExperience.StudentEducationalExperienceDO;
import cn.iocoder.yudao.module.member.dal.mysql.curriculumVitaeSendRecord.CurriculumVitaeSendRecordMapper;
import cn.iocoder.yudao.module.member.dal.mysql.interviewInvite.InterviewInviteMapper;
import cn.iocoder.yudao.module.member.dal.mysql.student.StudentMapper;
import cn.iocoder.yudao.module.member.dal.mysql.studentCurriculumVitae.StudentCurriculumVitaeMapper;
import cn.iocoder.yudao.module.member.dal.mysql.studentEducationalExperience.StudentEducationalExperienceMapper;
import cn.iocoder.yudao.module.system.api.message.MessageApi;
import cn.iocoder.yudao.module.system.api.message.dto.MessageCreateReqDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.sms.SmsSendApi;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.dal.redis.mail.MailRedisDAO;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 学生管理 Service 实现类
 *
 * @author 周枫皓
 */
@Service
@Validated
@Slf4j
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private FileApi fileApi;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private SmsSendApi smsSendApi;
    @Resource
    private StudentCurriculumVitaeMapper studentCurriculumVitaeMapper;
    @Resource
    private CurriculumVitaeSendRecordMapper curriculumVitaeSendRecordMapper;
    @Resource
    private InterviewInviteMapper interviewInviteMapper;
    @Resource
    private StudentEducationalExperienceMapper studentEducationalExperienceMapper;
    @Resource
    private MailRedisDAO mailRedisDAO;
    @Resource
    private MessageApi messageApi;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Value("${spring.profiles.active}")
    private String active;
    /**
     * 通过手机查询用户
     *
     * @param mobile 手机
     * @return 用户对象
     */
    @Override
    public StudentDO getStudentByMobile(String mobile) {
        return studentMapper.selectByMobile(mobile);
    }

    /**
     * 基于手机号创建用户。
     * 如果用户已经存在，则直接进行返回
     *
     * @param mobile     手机号
     * @param registerIp 注册 IP
     * @return 用户对象
     */
    @Override
    public StudentDO createStudentIfAbsent(@Mobile String mobile, String registerIp) {
        // 用户已经存在
        StudentDO user = studentMapper.selectByMobile(mobile);
        if (user != null) {
            user.setRegisterFlag(1);
            return user;
        }
        // 用户不存在，则进行创建
        return this.createUser(mobile, registerIp);
    }

    @Override
    public StudentDO createStudent(@Mobile String mobile, String registerIp) {
      return  this.createUser(mobile, registerIp);
    }

    @Override
    public StudentDO getStudent(@Mobile String mobile, String registerIp) {
        // 用户已经存在
        StudentDO user = studentMapper.selectByMobile(mobile);
        return user;
    }


    @Override
    public StudentDO getStudentBypassword(@Mobile String mobile, String password) {
        password=passwordEncoder.encode(password);
        return studentMapper.selectByPassword(mobile,password);
    }

    private StudentDO createUser(String mobile, String registerIp) {
        // 生成密码
        String password = IdUtil.fastSimpleUUID();
        LoginUser loginUser=SecurityFrameworkUtils.getLoginUser();
        // 插入用户
        StudentDO user = new StudentDO();
        user.setMobile(mobile);
        user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
        user.setPassword(passwordEncoder.encode(password)); // 加密密码
        user.setRegisterIp(registerIp);
        user.setCreator(mobile);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        studentMapper.insert(user);
        String title="注册成功，请实名认证";
        String message="注册成功，请尽快进行身份实名认证：<a href='http://47.107.248.245/test/#/auditId'  target='_blank'>http://47.107.248.245/test/#/auditId</a>";
        if(StringUtils.isNotBlank(active) && "prod".equals(active)){
            message="注册成功，请尽快进行身份实名认证：<a href='https://www.datarer.com/#/auditId'  target='_blank' >https://www.datarer.com/#/auditId</a>";
        }
        sendmessage(1l,user.getId(),title,message);
        user.setRegisterFlag(0);
        return user;
    }

    @Async
    void sendmessage(Long type, Long id, String title, String messageText){
        MessageCreateReqDTO messageCreateReqVO=new MessageCreateReqDTO();
        messageCreateReqVO.setPhone("");
        messageCreateReqVO.setType(type);
        messageCreateReqVO.setStatus("5");
        messageCreateReqVO.setStudentId(id);
        messageCreateReqVO.setStudentName("系统管理员");
        messageCreateReqVO.setRemark(messageText);
        messageCreateReqVO.setTitle(title);
        messageApi.sendMessage(messageCreateReqVO);
    }
    /**
     * 更新用户的最后登陆信息
     *
     * @param id      用户编号
     * @param loginIp 登陆 IP
     */
    @Override
    public void updateStudentLogin(Long id, String loginIp) {
        studentMapper.updateById(new StudentDO().setId(id)
                .setLoginIp(loginIp).setLoginDate(new Date()));
    }

    @Override
    public StudentDO getStudent(Long id) {
        return studentMapper.selectById(id);
    }

    @Override
    public void examine(String studentId,StudentUpdateReqVO updateReqVO){
        if(mailRedisDAO.hast("EXAMINE_"+updateReqVO.getId())){
            log.error("重复点击审核学生:"+updateReqVO.getId());
            return;
        }
        mailRedisDAO.set("EXAMINE_"+updateReqVO.getId(),"1",Duration.ofSeconds(3));
        StudentDO studentDO=studentMapper.selectById(updateReqVO.getId());
        if(studentDO==null){
            throw exception(STUDENT_NOT_EXISTS);
        }
        updateReqVO.setChecker(SecurityFrameworkUtils.getLoginUser().getUsername());
        if(updateReqVO.getIsmail().equals(1)){
            if(updateReqVO.getStatus().equals(1)){
                String tag=studentDO.getMobile();
                String code =MailUtils.codeFen();
                String str = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body><p style='font-size: 20px;font-weight:bold;'>亲爱的："+studentDO.getStudentName()+"，您好！</p>"
                        + "<p style='text-align:right; padding-right: 20px;'>请复制下方网页地址到浏览器地址栏中打开，完成邮箱验证：</p>"
                        + "<p style='text-align:right; padding-right: 20px;'>https://www.datarer.com/admin-api/system/mail/verification?type=student"+"&code="+code+"&tag="+ EncryptionUtil.desEncrypt(tag)
                        + "<a href='https://www.datarer.com/admin-api/system/mail/verification?type=student&code='"+code+"&tag="+ EncryptionUtil.desEncrypt(tag)+" style='font-size: 18px'>(认证链接)</a></p>"
                        + "<p style='text-align:; font-size: 18px; padding-right: 20px;'> 该链接有效期至"+ DateUtils.addDay(new Date(),1) +"请尽快认证</p>"
                        + "<p style='text-align:right; padding-right: 20px;'> " + sdf.format(new Date()) + "</p></body></html>";
                EmailInfo emailInfo=new EmailInfo();
                emailInfo.setToUser(studentDO.getEmail());
                emailInfo.setSubject("【数据学徒】请完成邮箱验证");
                emailInfo.setContent(str);
                mailRedisDAO.set(tag,code, Duration.ofDays(1));
//                MailUtils.sendHtmlMail(emailInfo);
                sendHtmlMail(emailInfo);
            }
        }
        this.updateStudent(updateReqVO);
        this.sendMessage(studentDO,updateReqVO);
        if(StringUtils.isNotBlank(studentDO.getMobile())){
            boolean isMatch= StrUtils.validMobile(studentDO.getMobile());
            if(isMatch){
                String title;
                String message;
                if(1==updateReqVO.getStatus()){
                    title="身份认证成功";
                    message="恭喜，您已身份认证成功，可以愉快地投递简历拉~";
                }else{
                    title="身份认证失败";
                    if(StringUtils.isNotBlank(active) && "prod".equals(active)){
                        message="身份认证失败，失败原因为："+updateReqVO.getRemark()+"，请重新进行身份实名认证：<a href='https://www.datarer.com/#/auditId'  target='_blank' >https://www.datarer.com/#/auditId</a>";
                    }else{
                        message="身份认证失败，失败原因为："+updateReqVO.getRemark()+"，请重新进行身份实名认证：<a href='http://47.107.248.245/test/#/auditId'  target='_blank'>http://47.107.248.245/test/#/auditId</a>";
                    }
                }
                sendmessage(1L,studentDO.getId(),title,message);
            }
        }
    }
    /**
     * 异步发送邮件
     * @param emailInfo
     */
//    @Async
    void sendHtmlMail(EmailInfo emailInfo){
//        MailUtils.sendHtmlMail(emailInfo);
        emailInfo.setEnvironment(active);
        System.out.println("学生审核---"+JSONObject.toJSONString(emailInfo));
        threadPoolTaskExecutor.execute(()->{
            HttpUtils.doPost("http://127.0.0.1:8085/demo/task/sendMail",JSONObject.toJSONString(emailInfo));
        });
    }
    /**
     * 发送面试通知短信
     * @param studentDO
     */
    private void sendMessage(StudentDO studentDO,StudentUpdateReqVO updateReqVO){
        SmsSendSingleToUserReqDTO smsSendSingleToUserReqDTO=new SmsSendSingleToUserReqDTO();
        smsSendSingleToUserReqDTO.setUserId(SecurityFrameworkUtils.getLoginUserId());
        smsSendSingleToUserReqDTO.setMobile(studentDO.getMobile());
        smsSendSingleToUserReqDTO.setTemplateCode("aliyun-student-examine-message");
        Map<String,Object> paraMap=new HashMap<>();
        paraMap.put("studentName",studentDO.getNickname());
        paraMap.put("result",convertAuthorizedStatus(updateReqVO.getStatus().toString()));
        smsSendSingleToUserReqDTO.setTemplateParams(paraMap);
        smsSendApi.sendSingleSmsToAdmin(smsSendSingleToUserReqDTO);
    }
    private String convertAuthorizedStatus(String authorizedStatus){
        if(authorizedStatus.equals("1")){
            return "通过";
        }
        if(authorizedStatus.equals("2")){
            return "未通过";
        }
        return "";
    }

    /**
     * 修改用户昵称
     *
     * @param studentId 用户id
     * @param nickname  用户新昵称
     */
    @Override
    public void updateStudentNickname(Long studentId, String nickname) {
        StudentDO user = this.checkUserExists(studentId);
        // 仅当新昵称不等于旧昵称时进行修改
        if (nickname.equals(user.getNickname())) {
            return;
        }
        StudentDO userDO = new StudentDO();
        userDO.setId(user.getId());
        userDO.setNickname(nickname);
        studentMapper.updateById(userDO);
    }


    @Override
    public Long createStudent(StudentCreateReqVO createReqVO) {
        // 插入
        StudentDO student = StudentConvert.INSTANCE.convert(createReqVO);
        studentMapper.insert(student);
        // 返回
        return student.getId();
    }

    @Override
    public void updateStudent(StudentUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateStudentExists(updateReqVO.getId());

        List<StudentDO> list = studentMapper.selectList("mobile", updateReqVO.getMobile());
        if(CollectionUtils.isNotEmpty(list)){
            List<Long> ids = list.stream().map(m -> m.getId()).collect(Collectors.toList());
            if(!ids.contains(updateReqVO.getId())){
                throw exception(AUTH_LOGIN_USER_EXIST);
            }
        }
        // 更新
        StudentDO updateObj = StudentConvert.INSTANCE.convert(updateReqVO);
        updateObj.setCheckDate(new Date());
        studentMapper.updateById(updateObj);
        StudentCurriculumVitaeDO updateReqDTO=new StudentCurriculumVitaeDO();
        updateReqDTO.setStudentId(updateReqVO.getId());
        updateReqDTO.setStudentName(updateReqVO.getStudentName());
        updateReqDTO.setSex(updateReqVO.getSex());
        updateReqDTO.setClan(updateReqVO.getClan());
        updateReqDTO.setPolitical(updateReqVO.getPolitical());
        updateReqDTO.setNativePlace(updateReqVO.getNativePlace());
        updateReqDTO.setLiveCity(updateReqVO.getLiveCity());
        updateReqDTO.setEmail(updateReqVO.getEmail());
        studentCurriculumVitaeMapper.update(updateReqDTO,new QueryWrapper<StudentCurriculumVitaeDO>().eq("student_id",updateReqVO.getId()));
    }

    @Override
    public void deleteStudent(Long id) {
        // 校验存在
        this.validateStudentExists(id);
        //删除简历
        studentCurriculumVitaeMapper.delete(new QueryWrapper<StudentCurriculumVitaeDO>().eq("student_id",id));
        //删除面试邀约记录
        interviewInviteMapper.delete(new QueryWrapper<InterviewInviteDO>().eq("student_id",id));
        //删除发送记录
        curriculumVitaeSendRecordMapper.delete(new QueryWrapper<CurriculumVitaeSendRecordDO>().eq("student_id",id));
        // 删除学生
        studentMapper.deleteById(id);
    }

    private void validateStudentExists(Long id) {
        if (studentMapper.selectById(id) == null) {
            throw exception(STUDENT_NOT_EXISTS);
        }
    }

    @Override
    public List<StudentDO> getStudentList(Collection<Long> ids) {
        return studentMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<StudentDO> getStudentPage(StudentPageReqVO pageReqVO) {
        return studentMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<StudentInfoRespVO> getStudentInfoPage(StudentPageReqVO pageReqVO) {
        IPage<StudentInfoRespVO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        // 转换返回
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(pageReqVO.getStudentName())){
            params.put("studentName",pageReqVO.getStudentName());
        }
        if(CollectionUtils.isNotEmpty(pageReqVO.getStatus())){
            params.put("status",pageReqVO.getStatus().get(0));
        }
        if(StringUtils.isNotBlank(pageReqVO.getMobile())){
            params.put("mobile",pageReqVO.getMobile());
        }
        if(StringUtils.isNotBlank(pageReqVO.getJobStatus())){
            params.put("jobStatus",pageReqVO.getJobStatus());
        }
        if(StringUtils.isNotBlank(pageReqVO.getSex())){
            params.put("sex",pageReqVO.getSex());
        }
        if(StringUtils.isNotBlank(pageReqVO.getLiveCity())){
            params.put("liveCity",pageReqVO.getLiveCity());
        }
        if(StringUtils.isNotBlank(pageReqVO.getEducationalExperience())){
            params.put("educationalExperience",pageReqVO.getEducationalExperience());
        }
        if(StringUtils.isNotBlank(pageReqVO.getInternshipDesire())){
            params.put("internshipDesire",pageReqVO.getInternshipDesire());
        }
//        if(null!=pageReqVO.getMaxAge()){
//            params.put("maxAge",pageReqVO.getMaxAge());
//        }
//        if(null!=pageReqVO.getMinAge()){
//            params.put("minAge",pageReqVO.getMinAge());
//        }
        if(null!=pageReqVO.getStartDate()){
            params.put("startDate",pageReqVO.getStartDate());
        }
        if(null!=pageReqVO.getEndDate()){
            params.put("endDate",pageReqVO.getEndDate());
        }
        if(null!=pageReqVO.getCollectStatus()){
            params.put("collectStatus",pageReqVO.getCollectStatus());
        }
        params.put("relationType",pageReqVO.getRelationType());
        Long loginUserId = WebFrameworkUtils.getLoginUserId();
        params.put("loginUserId",loginUserId);
        List<StudentInfoRespVO> list = studentMapper.getStudentInfoPage(mpPage, params);
        if(CollectionUtils.isNotEmpty(list)){
            list.stream().forEach(m->{
//                StudentCurriculumVitaeDO studentCurriculumVitae=
//                        studentCurriculumVitaeMapper.selectOne(new QueryWrapper<StudentCurriculumVitaeDO>().eq("student_id",m.getId()).last(" order by create_time asc limit 1"));
//                if(null!=studentCurriculumVitae && studentCurriculumVitae.getId()!=null ){
//                    List<StudentEducationalExperienceDO> studentEducationalExperienceDOS = studentEducationalExperienceMapper.selectListByStudentId(studentCurriculumVitae.getId());
//                    m.setEducationalExperience(StudentEducationalExperienceConvert.INSTANCE.convertList(studentEducationalExperienceDOS));
//                }
                m.setEducationalExperience(studentEducationalExperienceMapper.getStudentEducationalExperienceByStudentId(m.getId()));
            });
        }
        mpPage.setRecords(list);
        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal());
    }

    @Override
    public List<StudentEducationalExperienceRespVO> getStudentEducationalExperienceByStudentId(Long studentId){
        return studentEducationalExperienceMapper.getStudentEducationalExperienceByStudentId(studentId);
    }

    @Override
    public PageResult<StudentInfoRespVO> getPushStudentInfoPage(StudentInfoPageReqVO pageReqVO) {
        IPage<StudentInfoRespVO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        // 转换返回
        Map<String, Object> params = new HashMap<>();
        if(null!=pageReqVO.getStatus()){
            params.put("status",pageReqVO.getStatus() );
        }
        if(StringUtils.isNotBlank(pageReqVO.getStudentName())){
            params.put("studentName",pageReqVO.getStudentName());
        }
        if(StringUtils.isNotBlank(pageReqVO.getMobile())){
            params.put("mobile",pageReqVO.getMobile());
        }
        if(null==pageReqVO.getRiceFlag()){
            pageReqVO.setRiceFlag(0);
        }
        params.put("riceFlag",pageReqVO.getRiceFlag());
        if(StringUtils.isNotBlank(pageReqVO.getSex())){
            params.put("sex",pageReqVO.getSex());
        }
        if(null!=pageReqVO.getStartDate()){
            params.put("startDate",pageReqVO.getStartDate());
        }
        if(null!=pageReqVO.getEndDate()){
            params.put("endDate",pageReqVO.getEndDate());
        }
        if(StringUtils.isNotBlank(pageReqVO.getSchoolName())){
            params.put("schoolName",pageReqVO.getSchoolName());
        }
        if(StringUtils.isNotBlank(pageReqVO.getEducationalBackground())){
            params.put("educationalBackground",pageReqVO.getEducationalBackground());
        }
        if(StringUtils.isNotBlank(pageReqVO.getMajor())){
            params.put("major",pageReqVO.getMajor());
        }
        if(StringUtils.isNotBlank(pageReqVO.getIsOverseasStudy())){
            params.put("isOverseasStudy",pageReqVO.getIsOverseasStudy());
        }
        if(StringUtils.isNotBlank(pageReqVO.getSchoolName())
        ||StringUtils.isNotBlank(pageReqVO.getEducationalBackground())
        ||StringUtils.isNotBlank(pageReqVO.getMajor())
        ||StringUtils.isNotBlank(pageReqVO.getIsOverseasStudy()) ){
            params.put("educationFlag","1");
        }

        if(StringUtils.isNotBlank(pageReqVO.getPolitical())){
            params.put("political",pageReqVO.getPolitical());
        }
        if(StringUtils.isNotBlank(pageReqVO.getLiveCity())){
            params.put("liveCity",pageReqVO.getLiveCity());
        }
        if(StringUtils.isNotBlank(pageReqVO.getNativePlace())){
            params.put("nativePlace",pageReqVO.getNativePlace());
        }
        if(StringUtils.isNotBlank(pageReqVO.getLanguageAbility())){
            params.put("languageAbility",pageReqVO.getLanguageAbility());
        }
        if(StringUtils.isNotBlank(pageReqVO.getInternshipDesire())){
            params.put("internshipDesire",pageReqVO.getInternshipDesire());
        }
        if(StringUtils.isNotBlank(pageReqVO.getIsRealName())){
            params.put("isRealName",pageReqVO.getIsRealName());
        }
        if(StringUtils.isNotBlank(pageReqVO.getInJobTime())){
            params.put("inJobTime",pageReqVO.getInJobTime());
        }
        if(StringUtils.isNotBlank(pageReqVO.getJobStatus())){
            params.put("jobStatus",pageReqVO.getJobStatus());
        }

        List<StudentInfoRespVO> list = studentMapper.getPushStudentInfoPage(mpPage, params);
        mpPage.setRecords(list);
        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal());
    }

    @Override
    public List<StudentDO> getStudentList(StudentExportReqVO exportReqVO) {
        return studentMapper.selectList(exportReqVO);
    }

    /**
     * 修改用户头像
     *
     * @param studentId   用户id
     * @param inputStream 头像文件
     * @return 头像url
     */
    @Override
    public String updateStudentAvatar(Long studentId, InputStream inputStream) throws Exception {
        this.checkUserExists(studentId);
        // 创建文件
        String avatar = fileApi.createFile(IoUtil.readBytes(inputStream));
        // 更新头像路径
        studentMapper.updateById(StudentDO.builder().id(studentId).avatar(avatar).build());
        return avatar;
    }

    /**
     * 修改手机
     *
     * @param studentId 用户id
     * @param reqVO     请求实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStudentMobile(Long studentId, AppUserUpdateMobileReqVO reqVO) {
        // 检测用户是否存在
        checkUserExists(studentId);
        // TODO 芋艿：oldMobile 应该不用传递

        // 校验旧手机和旧验证码
        smsCodeApi.useSmsCode(new SmsCodeUseReqDTO().setMobile(reqVO.getOldMobile()).setCode(reqVO.getOldCode())
                .setScene(SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene()).setUsedIp(getClientIP()));
        // 使用新验证码
        smsCodeApi.useSmsCode(new SmsCodeUseReqDTO().setMobile(reqVO.getMobile()).setCode(reqVO.getCode())
                .setScene(SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene()).setUsedIp(getClientIP()));

        // 更新用户手机
        studentMapper.updateById(StudentDO.builder().id(studentId).mobile(reqVO.getMobile()).build());
    }

    @Override
    public Integer getStudentRegistCount(String startDate, String endDate) {
        return studentMapper.getStudentRegistCount(startDate,endDate);
    }


    @VisibleForTesting
    public StudentDO checkUserExists(Long id) {
        if (id == null) {
            return null;
        }
        StudentDO user = studentMapper.selectById(id);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
        return user;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String studentImportExcel(List<StudentExcelImportVO> list) {
        String sMsg="总共";
        if(CollectionUtils.isNotEmpty(list)){
            sMsg+=list.size()+"条";
            StudentDO std=null;
            StudentCurriculumVitaeDO scv=null;
            StudentEducationalExperienceDO sed=null;
            int num=0;
            StringBuffer sb=new StringBuffer();
            for (int i=0;i<list.size();i++) {
                StudentExcelImportVO s=list.get(i);
                if(StringUtils.isBlank(s.getMobile()) || StringUtils.isBlank(s.getStudentName())){
                    sb.append(",第").append(i+1).append("手机号或者姓名为空,");
                    continue;
                }
                num++;
                Long aLong = studentMapper.selectCount(StudentDO::getMobile, s.getMobile());
                if(null==aLong || 0L==aLong){
                    std=new StudentDO();
                    BeanUtils.copyProperties(s,std);
                    std.setStatus(1);
                    if("在校".equals(s.getIdentify())){
                        std.setIdentify("0");
                    }else{
                        std.setIdentify("1");
                    }
                    std.setNickname(s.getStudentName());
                    std.setUniversityName(s.getSchoolName());
                    std.setEducation(s.getEducationalBackground());
                    std.setBirthday(DateUtils.strToDate(s.getStuBirthday()));
                    if("是".equals(s.getDiploma())){
                        std.setDiploma("yes");
                    }else{
                        std.setDiploma("no");
                    }
                    if("国外".equals(s.getStudentAbroad())){
                        std.setStudentAbroad(0);
                    }else{
                        std.setStudentAbroad(1);
                    }
                    std.setSpecialty(s.getMajor());
                    std.setIsRealName("yes");
                    studentMapper.insert(std);

                    scv=new StudentCurriculumVitaeDO();
                    BeanUtils.copyProperties(s,scv);
                    scv.setStudentId(std.getId());
                    scv.setPhoneNumber(s.getMobile());
                    scv.setUniversityName(s.getSchoolName());
                    scv.setEducation(s.getEducationalBackground());
                    scv.setSpecialty(s.getMajor());
                    scv.setBirthday(DateUtils.strToDate(s.getStuBirthday()));
                    if("在校".equals(s.getIdentify())){
                        scv.setIdentify("0");
                    }else{
                        scv.setIdentify("1");
                    }
                    if("是".equals(s.getDiploma())){
                        scv.setDiploma("yes");
                    }else{
                        scv.setDiploma("no");
                    }
                    scv.setPublicStatus("0");
                    studentCurriculumVitaeMapper.insert(scv);

                    sed=new StudentEducationalExperienceDO();
                    BeanUtils.copyProperties(s,sed);
                    sed.setStudentId(scv.getId());
                    if("是".equals(s.getFullTime())){
                        sed.setFullTime("1");
                    }else{
                        sed.setFullTime("0");
                    }
                    if("是".equals(s.getDiploma())){
                        sed.setDiploma("1");
                    }else{
                        sed.setDiploma("0");
                    }
                    studentEducationalExperienceMapper.insert(sed);
                }else{
                    sb.append(",第").append(i+1).append("手机号已存在");
                }
            }
            sMsg+=",执行"+num+"条成功";
            if(StringUtils.isNotBlank(sb.toString())){
                sMsg+=sb.toString() ;
            }
        }else{
            sMsg+="0条数据,执行0条成功";
        }
        return sMsg;
    }
}
